<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <!-- 头部 -->
        <HeadSearch :category="1" @addEvent="addFn" @Asearch="Asearch" />
        <el-table
          :data="tableData"
          border
          style="width: 100%"
          height="calc(100vh - 247px)"
        >
          <el-table-column
            prop="image"
            label="图片"
            width="300"
            align="center"
          >
            <template v-slot="{row}">
              <img :src="row.image" style="width: 200px;height: 200px;">
            </template>
          </el-table-column>
          <el-table-column
            prop="title"
            label="标题"
            width="180"
            align="center"
          />
          <el-table-column
            prop="desc"
            label="介绍"
            align="center"
          />
          <el-table-column label="操作" align="center">
            <template v-slot="{row}">
              <el-button type="primary" size="small" @click="editFn(row.id)">编辑</el-button>
              <el-button type="danger" size="small" @click="deleteFn(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            :current-page="currentPage"
            :page-sizes="[2, 10, 15, 20]"
            :page-size="pagersize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>

      </el-card>
      <el-dialog
        :title="formData.id?'编辑分类':'新增分类'"
        :visible.sync="dialogVisible"
        width="70%"
        @close="closeFn"
      >
        <el-form ref="form" :rules="rules" label-width="80px" :model="formData">
          <el-form-item label="标题" prop="title">
            <el-input v-model="formData.title" />
          </el-form-item>
          <el-form-item label="描述" prop="desc">
            <el-input v-model="formData.desc" />
          </el-form-item>
          <el-form-item label="封面" prop="image">
            <TuPian ref="tuPian" @addEvent="addEvent" />
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="closeFn">取 消</el-button>
          <el-button type="primary" @click="additionFn">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import HeadSearch from '@/components/HeadSearch.vue'
import TuPian from './components/tupian.vue'
import { getCategory, postCategories, delCategories, getCategories, putCategories } from '@/api/category'

export default {
  components: { HeadSearch, TuPian },
  data() {
    return {
      tableData: [],
      formData: {
        title: '',
        desc: '',
        image: ''
      },
      dialogVisible: false,
      rules: {
        title: [
          { required: 'true', message: '标题不能为空', trigger: 'blur' },
          { min: 1, max: 20, message: '文字不能超过20个字', trigger: 'blur' }
        ],
        desc: [
          { required: 'true', message: '内容不能为空', trigger: 'blur' },
          { min: 1, max: 200, message: '文字不能超过200个字', trigger: 'blur' }
        ]
      },
      currentPage: 1, // 当前页码
      pagersize: 2, // 每页条数
      page: {
        _limit: 2, // 显示的数据
        _start: 0, // 从几条开始显示
        title_contains: ''// 搜索的内容
      },
      total: 0

    }
  },
  created() {
    this.getCategorys()
    this.getCategoryFn()
  },
  methods: {

    // 编辑
    editFn(id) {
      this.dialogVisible = true
      getCategories(id).then((res) => {
        this.formData = res
        this.$refs.tuPian.filelist.push({
          url: res.image
        })
      })
    },
    // 删除
    deleteFn(id) {
      this.$confirm('是否确定要删除', '删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await delCategories(id)
        if (this.tableData.length === 1 && this.currentPage > 1) {
          this.currentPage = this.currentPage - 1
          this.page._start = (this.currentPage - 1) * this.page._limit
        }
        this.$message.success('删除成功')
        this.getCategorys()
        this.getCategoryFn()
      }).catch(() => {
        this.$message.error('取消删除')
      })
    },
    async getCategorys() { // 获取分类数据
      this.tableData = await getCategory(this.page)
    },
    async getCategoryFn(input) {
      const res = await getCategory({ _limit: 999, _start: 0, title_contains: input })
      this.total = res.length
    },
    // 搜索
    Asearch(input) {
      console.log(input)
      this.page.title_contains = input
      this.currentPage = 1
      this.page._start = 0
      this.getCategorys()
      this.getCategoryFn(input)
    },
    // 添加
    async additionFn() {
      await this.$refs.form.validate()
      if (this.formData.id) {
        this.formData.image = this.$refs.tuPian.filelist[0].url
        await putCategories(this.formData)
        this.$message.success('编辑成功')
      } else {
        await postCategories({
          title: this.formData.title,
          desc: this.formData.desc,
          image: this.formData.image

        })
        this.$message.success('添加成功')
      }

      this.closeFn()

      this.getCategorys()
      this.getCategoryFn()
      this.page.title_contains = ''// 搜索
    },
    // 关闭弹窗
    closeFn() {
      this.dialogVisible = false
      // 清空表单
      this.formData = {
        title: '',
        desc: '',
        image: this.$refs.tuPian.filelist = []
      }
      this.$refs.form.resetFields()
    },
    addFn() {
      this.dialogVisible = true
    },
    handleSizeChange(size) {
      this.page._limit = size
      this.pagersize = size
      if (this.input === '') {
        this.getCategorys()
      } else {
        this.getCategorys(this.page)
      }
    },
    handleCurrentChange(page) {
      this.currentPage = page
      this.page._start = (page - 1) * this.page._limit
      this.getCategorys()
    },
    addEvent(file) {
      this.formData.image = file[0].url
      console.log(145, this.formData.image)
    }
  }
}
</script>

<style lang='scss'>

</style>
